package com.shelpe.services.sinbad.dto.common;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;

import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.Data;

@Data
public class PagableList<E> {

	private List<E> contents;
	
	private long total;
	@JsonProperty("page_size")
	private int pageSize;
	@JsonProperty("page_number")
	private int pageNumber;
	@JsonProperty("page_total")
	private int pageTotal;
	
	public void add(E content){
		if(this.contents == null){
			this.contents = new ArrayList<E>();
		}
		this.contents.add(content);
	}
	
	@SuppressWarnings("rawtypes")
	public void from(Page page){
		this.total = page.getTotalElements();
		this.pageNumber = page.getNumber();
		this.pageSize = page.getSize();
		this.pageTotal = page.getTotalPages();
	}
	
	public static PageableBuilder builder(int page, int size){
		return new PageableBuilder(page, size);
	}
	
	public static class PageableBuilder{
		private int page;
		private int size;
		private Direction direction = Direction.DESC;
		private String field;
		
		public PageableBuilder(int page, int size){
			this.page = page;
			this.size = size;
		}
		
		public PageableBuilder direction(String direct){
			this.direction = Direction.fromStringOrNull(direct);
			return this;
		}
		
		@SuppressWarnings("rawtypes")
		public PageableBuilder sort(String field, Class c){
			for(Field f:c.getDeclaredFields()){
				JsonProperty jp = f.getAnnotation(JsonProperty.class);
				if(jp != null && jp.value() != null && jp.value().equals(field)){
					field = f.getName();
					break;
				}
			}
			this.field = field;
			return this;
		}
		
		public PageableBuilder sort(String field){
			this.field = field;
			return this;
		}
		
		public PageRequest build(){
			PageRequest pageable = new PageRequest(page, size, this.direction, this.field);
			return pageable;
		}
	}
}
